<?php
/**
 * 分享推广
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-03-28
 * Time: 下午 11:26
 */
namespace App;
use Model\ActivityMod;
use Model\QrcodeMod;
use Model\ShareMod;
use Pub\tool\Tool;
use Pub\wx\KeywordReply;
use Pub\wx\Qrcode;

class Share extends Action
{
	private $Activity = null;  //活动
	private $Share = null;   //活动推广分享表
	private $Qrocde = null;  //模块二维码
	private $WxQrcode = null;  //微擎二维码
	private $Keyword = null;  //微擎关键词回复

    private $_temp_remote_poster_path = '';  //临时远程文件

	public function __construct()
	{
		parent::__construct();
		$this->Share = new ShareMod();
	}

	/**
	 * 后台获取一个活动的推广数据
	 */
	public function findData()
	{
		$this->Activity = new ActivityMod();
		$_activity = $this->Activity->findOne(array('id'=>$this->_gpc['activity_id']),array('name'));
		if($_activity){
			$_share = $this->setting();
			$_activity = array_merge($_activity,$_share);
			$this->_result = array('status'=>'success','data'=>$_activity);
		}
		$this->result($this->_result);
	}

	/**
	 * 获取分享推广配置
	 */
	private function setting()
	{
		$_share = $this->Share->findOne(array('activity_id'=>$this->_gpc['activity_id']),array('open_share','add_bz','take_m','qr_width','qr_height','qr_left','qr_top','poster_path'));
		if($_share){
			$_share['poster_url'] = tomedia($_share['poster_path']);
			return $_share;
		}else{
			$this->Share->insert(array(
				'activity_id'=>$this->_gpc['activity_id']
			));
			return $this->setting();
		}
	}

	/**
	 * 设置活动的分享配置
	 */
	public function setSetting()
	{
		cache_delete('kuyuan_vbz_activity_'.$this->_gpc['activity_id']);
		load()->func('file');
		$_poster_filename = ATTACHMENT_ROOT.'kuyuan_vbz/'.$this->_uniacid.'/poster/';
		rmdirs($_poster_filename);
		$_data = $this->_gpc['data'];
		$_data['edit_time'] = TIMESTAMP;
		if($this->Share->update($_data,array('activity_id'=>$this->_gpc['activity_id']))){
			$this->_result = array('status'=>'success');
		}
		$this->result($this->_result);
	}

	/**
	 * 获取分享数据
	 */
	public function share()
	{
		$this->Activity = new ActivityMod();
		$_result = $this->Activity->findOne(array('uniacid' => $this->_uniacid,'id' => $this->_gpc['activity_id']), array('name','brief','cover'));
		$_result['cover'] = tomedia($_result['cover']);
		$_result['share_url'] = murl('entry//index',array('m'=>'kuyuan_vbz','activity_id'=>$this->_gpc['activity_id'],'share_uid'=>$this->_gpc['uid'],'route'=>urlencode('#/activity/'.$this->_gpc['activity_id'].'/'.$this->_gpc['uid'])),true,true);
		$this->_result = array('status'=>'success','data'=>$_result);
		$this->result($this->_result);
	}

	/**X
	 * 获取二维码响应链接
	 */
	public function qrcode()
	{
		//查询二维码是否过期
		$this->Qrocde = new QrcodeMod();
		$_qrcode = $this->Qrocde->findOne(array('uid'=>$this->_gpc['uid'],'activity_id'=>$this->_gpc['activity_id'],'type'=>1),array('id','past_time','url','scene_id'));
		if($_qrcode && $_qrcode['past_time']>TIMESTAMP){
			$this->_result = array('status'=>'success','data'=>$_qrcode['url']);
			$this->result($this->_result);
		}
		if($_qrcode){
			//已过期
			$this->WxQrcode = new Qrcode();
			if($_wx_qr = $this->WxQrcode->update($_qrcode['scene_id'])){
				$_edit_qrcode = $this->Qrocde->update(
					array(
						'past_time'=>TIMESTAMP + $_wx_qr['expire_seconds'],
						'url'=>$_wx_qr['url'],
						'ticket'=>$_wx_qr['ticket']
					),
					array('id'=>$_qrcode['id'])
				);
				if($_edit_qrcode){
					$this->_result = array('status'=>'success','data'=>$_wx_qr['url']);
					$this->result($this->_result);
				}else{
					$this->_result = array('status'=>'error','err_status'=>6,'err_msg'=>'操作失败:6');
					$this->result($this->_result);
				}
			}else{
				$this->_result = array('status'=>'error','err_status'=>7,'err_msg'=>'操作失败:7');
				$this->result($this->_result);
			}
		}else{
			//未生成
			$_response_keyword = Tool::createCode();
			$this->Keyword = new KeywordReply($_response_keyword);
			$this->Keyword->add();
			$this->WxQrcode = new Qrcode($_response_keyword);
			if($_wx_qr = $this->WxQrcode->create()){
				$_add_qrcode = $this->Qrocde->insert(array(
					'uniacid'=>$this->_uniacid,
					'uid'=>$this->_gpc['uid'],
					'activity_id'=>$this->_gpc['activity_id'],
					'scene_id'=>$_wx_qr['scene_id'],
					'response_keyword'=>$_response_keyword,
					'past_time'=>TIMESTAMP+$_wx_qr['expire_seconds'],
					'url'=>$_wx_qr['url'],
					'ticket'=>$_wx_qr['ticket'],
					'type'=>1
				));
				if($_add_qrcode){
					$this->_result = array('status'=>'success','data'=>$_wx_qr['url']);
					$this->result($this->_result);
				}else{
					$this->_result = array('status'=>'error','err_status'=>8,'err_msg'=>'操作失败:8');
					$this->result($this->_result);
				}
			}else{
				$this->_result = array('status'=>'error','err_status'=>9,'err_msg'=>'操作失败:9');
				$this->result($this->_result);
			}
		}
	}


	/**
	 * 前端返回指定用户的分享海报
	 */
	public function findPoster()
	{
		$_file = 'kuyuan_vbz/'.$this->_uniacid.'/poster/'.$this->_gpc['activity_id'].'-'.$this->_gpc['uid'].'.jpg';
		$_dir = ATTACHMENT_ROOT.'kuyuan_vbz/'.$this->_uniacid.'/poster/';
		$_filename = ATTACHMENT_ROOT.$_file;
		$_url = $this->_w['attachurl_local'].$_file;
		if(is_file($_filename)){
			$this->_result = array('status'=>'success','data'=>$_url);
			$this->result($this->_result);
		}
		//生成的海报
		$_poster_w = 640;
		$_poster_h = 1136;
		$_poster = imagecreatetruecolor($_poster_w,$_poster_h);

		//背景图片资源
		$_bg_resource = $this->findPosterBgResource();
		$_bg = $_bg_resource['resource'];
		$_bg_w = $_bg_resource['width'];
		$_bg_h = $_bg_resource['height'];
		$_qr_w = $_bg_resource['qr_w'];
		$_qr_h = $_bg_resource['qr_h'];
		$_qr_left = $_bg_resource['qr_left'];
		$_qr_top = $_bg_resource['qr_top'];

		//二维码资源
		$_qrcode_resource = $this->findQrcodeResource();
		$_qrcode = $_qrcode_resource['resource'];
		$_qrcode_filename = $_qrcode_resource['filename'];
		$_qrcode_w = $_qrcode_resource['width'];
		$_qrcode_h = $_qrcode_resource['height'];

		//合并背景
		imagecopyresampled($_poster,$_bg,0,0,0,0,$_poster_w,$_poster_h,$_bg_w,$_bg_h);

		//合并二维码
		imagecopyresampled($_poster,$_qrcode,$_qr_left,$_qr_top,0,0,$_qr_w,$_qr_h,$_qrcode_w,$_qrcode_h);
		unlink($_qrcode_filename);
		if($this->_temp_remote_poster_path != '') unlink($this->_temp_remote_poster_path);

		//输出
		if(!is_dir($_dir)) mkdir($_dir,0777,true);
		imagejpeg($_poster,$_filename);
		imagedestroy($_poster);
		imagedestroy($_bg);
		imagedestroy($_qrcode);
		$this->_result = array('status'=>'success','data'=>$_url);
		$this->result($this->_result);
	}

	/**
	 * 打开背景图片资源
	 */
	private function findPosterBgResource()
	{
		$_share = $this->Share->findOne(array('activity_id'=>$this->_gpc['activity_id']),array('poster_path','qr_width','qr_height','qr_left','qr_top'));
		$_bg_file = ATTACHMENT_ROOT.$_share['poster_path'];
		if(!is_file($_bg_file)){
            //获取不到本地图片，可能是开启了远程附件，获取远程资源，生成海报后在删除
            $_suffix = end(explode('.',$_share['poster_path']));
            $_bg_file_dir = ATTACHMENT_ROOT.'kuyuan_vbz/'.$this->_uniacid.'/poster_bg/';
            if(!is_dir($_bg_file_dir)) mkdir($_bg_file_dir,0777,true);
            $this->_temp_remote_poster_path = $_bg_file = $_bg_file_dir.$this->_gpc['activity_id'].'.'.$_suffix;
            file_put_contents($_bg_file,$this->findRemoteBgResource($_share['poster_path']));
        }
		list($_width,$_height) = getimagesize($_bg_file);
		return array('resource'=>$this->openImg($_bg_file),'width'=>$_width,'height'=>$_height,'qr_w'=>$_share['qr_width']*2,'qr_h'=>$_share['qr_height']*2,'qr_left'=>$_share['qr_left']*2,'qr_top'=>$_share['qr_top']*2);
	}

    /**
     * 获取远程资源
     */
	private function findRemoteBgResource($_url)
    {
        global $_W;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($ch, CURLOPT_URL,$_W['attachurl_remote'].$_url);
        curl_setopt($ch, CURLOPT_REFERER, $_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

	/**
	 * 获取二维码资源
	 */
	private function findQrcodeResource()
	{
		$_url = murl('entry//index',array('m'=>'kuyuan_vbz','activity_id'=>$this->_gpc['activity_id'],'share_uid'=>$this->_gpc['uid'],'route'=>urlencode('#/activity/'.$this->_gpc['activity_id'].'/'.$this->_gpc['uid'])),true,true);
		$Qrcode = new \Endroid\QrCode\QrCode($_url);
		$Qrcode->setImageType('png');
		$Qrcode->setSize(300);
		$_dir = ATTACHMENT_ROOT.'kuyuan_vbz/'.$this->_uniacid.'/poster/';
		if(!is_dir($_dir)) mkdir($_dir,0777,true);
		$_filename = $_dir.$this->_gpc['uid'].'qr.png';
		$Qrcode->save($_filename);
		list($_qrcode_w,$_qrcode_h) = getimagesize($_filename);
		return array('resource'=>$this->openImg($_filename),'filename'=>$_filename,'width'=>$_qrcode_w,'height'=>$_qrcode_h);
	}

	/**
	 * 打开指定图片
	 * @param $_filename  图片文件路径
	 */
	private function openImg($_filename)
	{
		$_postfix = end(explode('.',$_filename));
		switch ($_postfix){
			case 'png':
				return imagecreatefrompng($_filename);
				break;
			case 'jpg':
				return imagecreatefromjpeg($_filename);
				break;
			case 'gif':
				return imagecreatefromgif($_filename);
				break;
		}
	}

}